/**
 * 主从部署方式：
 * Config config = new Config();
 * config.useMasterSlaveServers()
 *         //设置redis主节点
 *         .setMasterAddress("redis://192.168.1.120:6379")
 *         //设置redis从节点
 *         .addSlaveAddress("redis://192.168.1.130:6379", "redis://192.168.1.140:6379");
 * RedissonClient redisson = Redisson.create(config);
 *
 * 集群部署方式：cluster方式至少6个节点,3主3从，3主做sharding，3从用来保证主宕机后可以高可用
 * Config config = new Config();
 * config.useClusterServers()
 *         .setScanInterval(2000)//集群状态扫描间隔时间，单位是毫秒
 *         .addNodeAddress("redis://192.168.1.120:6379")
 *         .addNodeAddress("redis://192.168.1.130:6379")
 *         .addNodeAddress("redis://192.168.1.140:6379")
 *         .addNodeAddress("redis://192.168.1.150:6379")
 *         .addNodeAddress("redis://192.168.1.160:6379")
 *         .addNodeAddress("redis://192.168.1.170:6379");
 * RedissonClient redissonClient = Redisson.create(config);
 *
 * 哨兵部署方式：sentinel是采用 Paxos拜占庭协议，一般sentinel至少3个节点
 *
 * Config config = new Config();
 * config.useSentinelServers()
 *         .setMasterName("my-sentinel-name")
 *         .addSentinelAddress("redis://192.168.1.120:6379")
 *         .addSentinelAddress("redis://192.168.1.130:6379")
 *         .addSentinelAddress("redis://192.168.1.140:6379");
 * RedissonClient redisson = Redisson.create(config);
 */
public class RedPacketDelayQueue {

    private static final Logger LOGGER = LoggerFactory.getLogger(RedPacketDelayQueue.class);

    public static void main(String[] args) throws Exception {
        Config config = new Config();
        config.useSingleServer().setAddress("redis://127.0.0.1:6379").setPassword("123456").setDatabase(2);
        RedissonClient redissonClient = Redisson.create(config);
        /**
         * 红包目标队列
         */
        RBlockingQueue<RedPacketMessage> blockingRedPacketQueue
                = redissonClient.getBlockingQueue("redPacketDelayQueue");
        /**
         * 定时任务将到期的元素转移到目标队列
         */
        RDelayedQueue<RedPacketMessage> delayedRedPacketQueue
                = redissonClient.getDelayedQueue(blockingRedPacketQueue);

        /**
         * 延时信息入队列
         */
        delayedRedPacketQueue.offer(new RedPacketMessage(20200113), 3, TimeUnit.SECONDS);
        delayedRedPacketQueue.offer(new RedPacketMessage(20200114), 5, TimeUnit.SECONDS);
        delayedRedPacketQueue.offer(new RedPacketMessage(20200115), 10, TimeUnit.SECONDS);
        while (true){
            /**
             * 取出失效红包
             */
            RedPacketMessage redPacket = blockingRedPacketQueue.take();
            LOGGER.info("红包ID:{}过期失效",redPacket.getRedPacketId());
            /**
             * 处理相关业务逻辑：记录相关信息并退还剩余红包金额
             */
        }
    }
}
